// 双向循环链表
const { Node } = require("./SingleList");
const { DbList } = require("./DbList");

class CirDbList extends DbList {
  constructor() {
    super();
    this.head.next = this.head;
    this.head.prev = this.head;
  }
  // 向双向循环链表中插入数据
  insert(item, element) {
    let itemNode = this.find(item);
    let newNode = new Node(element);

    // 双向循环链表中插入是双向链表中间插入值的实现
    newNode.next = itemNode.next;
    itemNode.next.prev = newNode;
    itemNode.next = newNode;
    newNode.prev = itemNode;
    this.size++;
  }

  // 从双向循环链表中删除数据
  remove(item) {
    // 删除头节点
    if (item === "head") {
      this.head.next = this.head;
      this.head.prev = this.head;
      this.size = 0;
      return;
    }
    let currNode = this.find(item);
    if (currNode) {
      currNode.next.prev = currNode.prev;
      currNode.prev.next = currNode.next;
      this.size--;
    }
  }

  // 在尾部添加数据
  append(element) {
    let lastNode = this.findLast();
    let newNode = new Node(element);
    // lastNode.next指向head，head.prev重新被赋值为newNode
    lastNode.next = newNode;
    newNode.prev = lastNode;
    newNode.next = lastNode.next;
    lastNode.next.prev = newNode;

    this.size++;
  }
}

let test = new CirDbList();

test.insert("head", 1);
test.insert(1, 2);
test.insert(1, 1.5);
test.insert("head", 0.5);
test.display(); // head->0.5->1->1.5->2
test.remove(1.5);
test.display();
test.append(9);
test.display();
